﻿namespace BEGDC.CC.Web.UserControls.EV
{
    using System;
    using System.Data;
    using System.Drawing;
    using System.Web;
    using System.Web.UI.WebControls;
    using System.Web.UI.HtmlControls;
    using BEGDC.CC.Entity;
    using BEGDC.CC.BL.CCFlow.EV;
    using BEGDC.CC.BL.Common;
    using BEGDC.Utility.Castle;
    using BEGDC.CC.BL.Common.Query;
    using BEGDC.CC.BL.CCFlow.CR;
    using BEGDC.CC.BL.Workflow;

    /// <summary>
    ///		Summary description for ApproveApp.
    /// </summary>
    public class ApproveApp : BaseEV
    {
        //protected System.Web.UI.WebControls.CheckBoxList CBL_ASBLeader;
        protected System.Web.UI.WebControls.DataGrid dgASBLeaders;
        protected System.Web.UI.WebControls.Button ibtnApprove;
        protected System.Web.UI.WebControls.Button ibtnQuery;
        protected System.Web.UI.WebControls.Button ibtnReject;
        protected System.Web.UI.WebControls.Button ibtnReply;
        protected System.Web.UI.WebControls.TextBox lblCluster;
        //protected System.Web.UI.WebControls.Label lblApplicant;
        protected System.Web.UI.WebControls.Label lblProposedDate;
        protected System.Web.UI.WebControls.Label lblOptionalDate;
        protected System.Web.UI.WebControls.Label lblProposedTime;
        //protected System.Web.UI.WebControls.Label lblOptionalTime;
        protected System.Web.UI.WebControls.Label lblCompany;
        protected System.Web.UI.WebControls.Label lblVenue;
        protected System.Web.UI.HtmlControls.HtmlTableCell Activies;
        protected System.Web.UI.HtmlControls.HtmlTableCell VisitingPurpose;
        protected System.Web.UI.HtmlControls.HtmlInputHidden txtComments;
        protected System.Web.UI.HtmlControls.HtmlInputHidden txtEmployeeID;
        protected System.Web.UI.WebControls.TextBox tbOperationFlag;
        protected System.Web.UI.WebControls.TextBox tbOperationContent;
        //protected System.Web.UI.WebControls.Label lblApplicantValue;
        protected System.Web.UI.WebControls.Label lblDept;
        protected System.Web.UI.WebControls.Label lblDeptValue;
        protected System.Web.UI.WebControls.Label lblCATBranch;
        protected System.Web.UI.WebControls.Label lblCATBranchValue;
        protected System.Web.UI.WebControls.Label lblAccountValue;
        protected System.Web.UI.WebControls.Label lblAccount;
        protected System.Web.UI.HtmlControls.HtmlTable approvedArea;
        protected System.Web.UI.WebControls.DataGrid dtGridProExecutives;
        protected System.Web.UI.HtmlControls.HtmlTableCell ProposedExecutives;
        protected System.Web.UI.WebControls.TextBox tbComment;
        protected System.Web.UI.WebControls.DataGrid dgCustomerList;
        protected System.Web.UI.WebControls.Label Lb_CISWarning;
        protected System.Web.UI.WebControls.Label lblLegalEntity;
        protected BEGDC.CC.Web.Common.StampCtrl stampCtrl1;
        protected System.Web.UI.WebControls.Label lbAppNo;
        protected ASB.CC.Web.UserControls.RequesterInfoControl RequesterInfoControl;
        protected string Step
        {
            get
            {
                IQuery queryService = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as IQuery;
                FlowInstance flowInstance = queryService.QueryFlowInstance(this.AppID);
                if (flowInstance == null)
                    return "Close";
                else
                    return flowInstance.CurrentActiveStep.StepCode;
            }
        }
        protected bool IsQuery
        {
            get
            {
                string state = this.Request.QueryString["State"];
                if (state == null) return false;
                return state == SysDicItem.ProjectStatusFlag.QUERY;
            }
        }

        private int CustInfoID
        {
            get
            {
                if (ViewState["CustInfoID"] == null)
                    return 0;
                else
                    return Convert.ToInt32(ViewState["CustInfoID"]);
            }
            set
            {
                ViewState["CustInfoID"] = value;
            }
        }


        private void Page_Load(object sender, System.EventArgs e)
        {
            // Put user code to initialize the page here
            if (!IsPostBack)
            {
                base.InitCommonData();
                InitAppInfo();

                this.ibtnReply.Attributes.Add("onclick", "javascript:OpenReplyPane(" + Request.QueryString["flowid"] + ")");
                this.ibtnReject.Attributes["onclick"] = "javascript:OnReject();";
                this.ibtnApprove.Attributes["onclick"] = "javascript:OnApprove();";
                this.ibtnQuery.Attributes.Add("onclick", "javascript:OpenQueryPane(" + Request.QueryString["flowid"] + ")");

                BindCustAttendee();
                BindALAttendee();
                this.BindASBLeaders();
                if (this.Access != null)
                {
                    this.ControlStatusSetting(((UserControls.EVAccessControl)Access).IsReadOnlyForApp);
                }

                this.RequesterInfoControl.isReadOnly = true;
            }
        }

        protected int AppID
        {
            get
            {
                if (this.Application == null)
                    return 0;
                else
                    return this.Application.Id;
            }
        }

        #region Web Form Designer generated code
        override protected void OnInit(EventArgs e)
        {
            //
            // CODEGEN: This call is required by the ASP.NET Web Form Designer.
            //
            InitializeComponent();
            base.OnInit(e);
        }

        /// <summary>
        ///	Required method for Designer support - do not modify
        ///	the contents of this method with the code editor.
        /// </summary>
        private void InitializeComponent()
        {
            this.ibtnApprove.Click += new EventHandler(ibtnApprove_Click);
            this.ibtnReply.Click += new EventHandler(ibtnReply_Click);
            this.ibtnReject.Click += new EventHandler(ibtnReject_Click);
            this.ibtnQuery.Click += new EventHandler(ibtnQuery_Click);
            this.dgCustomerList.ItemDataBound += new System.Web.UI.WebControls.DataGridItemEventHandler(this.dgCustomerList_ItemDataBound);
            this.Load += new System.EventHandler(this.Page_Load);

        }
        #endregion

        /// <summary>
        /// 
        /// </summary>
        /// <param name="access"></param>
        private void ControlStatusSetting(bool isReadonly)
        {
            ButtonStatus();
        }

        private void ButtonStatus()
        {
            if (!this.IsCurrentStep(WorkTransition.EV_PSOApprove) && !this.IsCurrentStep(WorkTransition.EV_CATDirectorApprove))
            {
                this.ibtnApprove.Visible = false;
                this.ibtnQuery.Visible = false;
                this.ibtnReject.Visible = false;
                this.ibtnReply.Visible = false;
            }
            else if (Access != null)
            {
                if (Access.IsHideAllButton)
                {
                    this.ibtnApprove.Visible = false;
                    this.ibtnQuery.Visible = false;
                    this.ibtnReject.Visible = false;
                    this.ibtnReply.Visible = false;
                }
                else if (Access.IsQuery)
                {
                    this.ibtnApprove.Visible = false;
                    this.ibtnQuery.Visible = false;
                    this.ibtnReject.Visible = false;
                    this.ibtnReply.Visible = true;
                }
                else
                {
                    this.ibtnApprove.Visible = Access.IsButtonVisible(EVTransitionList.Approve);
                    this.ibtnQuery.Visible = Access.IsButtonVisible(EVTransitionList.Query);
                    this.ibtnReject.Visible = Access.IsButtonVisible(EVTransitionList.Reject);
                    this.ibtnReply.Visible = false;
                }
            }
        }

        private void SetStamp()
        {
            //			IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
            //			DataTable table = queryService.QueryActionLog( this.AppID );
            //			stampCtrl1.SetDataSource( table );
            //stampCtrl1.GetStampByAppID(this.AppID);
        }
        /// <summary>
        /// 
        /// </summary>
        private void InitAppInfo()
        {
            try
            {
                #region Init Application Information
                if (this.Application != null)
                {
                    if (this.Application != null && this.Application.AppNo != string.Empty)
                        this.lbAppNo.Text = " Application No:" + this.Application.AppNo;

                    //this.lblApplicantValue.Text = Application.RequesterNameEN;
                    this.lblDeptValue.Text = Application.RequesterDept;
                    if (Application.DepartmentName != null)
                    {
                        this.lblCATBranchValue.Text = Application.CATBranch;
                        this.lblCluster.Text = Application.Others;
                        //this.lblCluster.CssClass = "Cluster_Block";
                    }
                    if (Application.DepartmentType.DicItemKey == "CAT")
                    {
                        this.lblAccount.Visible = false;
                        this.lblAccountValue.Visible = false;
                    }
                    else
                    {
                        this.lblAccountValue.Text = Application.Account;
                    }

                    if (Application.LegalEntity != null)
                    {
                        this.lblLegalEntity.Text = Application.LegalEntity.LegalEntityName;
                    }
                    if (Application.RequestedDateFrom != Nullables.NullableDateTime.Default)
                    {
                        this.lblProposedDate.Text = WebUtility.FormatDateString(Application.RequestedDateFrom.Value);
                        this.lblProposedTime.Text = Application.RequestedDateFrom.Value.ToString("HH:mm");

                    }
                    if (Application.AlternateDateFrom != Nullables.NullableDateTime.Default)
                    {
                        this.lblOptionalDate.Text = WebUtility.FormatDateString(Application.AlternateDateFrom.Value);
                        //this.lblOptionalTime.Text = Application.AlternateDateFrom.Value.ToString("HH:mm");
                    }
                    this.Activies.InnerHtml = "&nbsp;" + Application.Activity;
                }
                #endregion

                #region Init CustomerInfo
                BEGDC.CC.BL.Common.Query.IQuery queryService = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.QueryService] as BEGDC.CC.BL.Common.Query.IQuery;
                CustomerInfo custInfo = queryService.GetCustomerInfo(this.AppID);

                if (custInfo != null)
                {
                    this.CustInfoID = custInfo.Id;
                    this.lblCompany.Text = custInfo.Company;
                    this.lblVenue.Text = custInfo.Venue;
                    if (custInfo.VisitObjective + string.Empty != string.Empty)
                        this.VisitingPurpose.InnerHtml = "&nbsp;" + custInfo.VisitObjective.Replace("\r\n", "<br>");
                }
                #endregion

            }
            catch (BEGDC.Utility.ExceptionManagement.GDCException gdcEx)
            {
                //todo
            }
        }

        private void BindCustAttendee()
        {
            DataTable CustomerDataTable = null;

            if (this.CustInfoID > 0)
            {
                IQuery queryService = AppContainer.Instance[ServiceConst.QueryService] as IQuery;
                CustomerDataTable = queryService.GetCustomerAttendeeList(this.CustInfoID);

                if (CustomerDataTable.Select("IsExisted='" + BEGDC.CC.BL.Common.CISFlag.NotExisted + "'").Length > 0)
                {
                    this.Lb_CISWarning.Visible = true;
                }
                else
                {
                    this.Lb_CISWarning.Visible = false;
                }

                this.dgCustomerList.DataSource = CustomerDataTable;
                this.dgCustomerList.DataBind();
            }


        }

        private void BindALAttendee()
        {
            DataTable AccompanyingAttendee = null;

            if (this.AppID > 0)
            {
                ICR crService = AppContainer.Instance[ServiceConst.CRService] as ICR;
                AccompanyingAttendee = crService.GetAccompanyingAttendeeList(this.AppID);
                this.dtGridProExecutives.DataSource = AccompanyingAttendee;
                this.dtGridProExecutives.DataBind();
            }


        }

        void ibtnApprove_Click(object sender, EventArgs e)
        {
            try
            {
                BEGDC.CC.BL.CCFlow.EV.IEV evService = BEGDC.Utility.Castle.AppContainer.Instance[BEGDC.CC.BL.Common.ServiceConst.EVService] as BEGDC.CC.BL.CCFlow.EV.IEV;
                System.Collections.IList arrayList = new System.Collections.ArrayList();
                arrayList.Add(this.Application);
                evService.ApproveEVRequest(arrayList, null);

                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");

            }
            catch
            {
            }
        }

        void ibtnQuery_Click(object sender, EventArgs e)
        {
            if (this.tbOperationFlag.Text == "query")
            {
                IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;
                string comment = "";
                if (Session["Comment"] != null)
                    comment = Session["Comment"].ToString();
                evService.Query(Convert.ToInt64(Request.QueryString["flowid"]), this.tbOperationContent.Text, comment);
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");

            }
        }

        private void ibtnDrawback_Click(object sender, System.Web.UI.ImageClickEventArgs e)
        {
            try
            {
                IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;
                evService.Drawback(this.Application, null);
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");
            }
            catch (BEGDC.Utility.ExceptionManagement.GDCException gdcEx)
            {

            }
        }

        void ibtnReject_Click(object sender, EventArgs e)
        {
            try
            {
                IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;
                evService.RejectCheckApp(this.Application, WebUtility.DeCodeString(this.Server, this.tbComment.Text));
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        private void dgCustomerList_ItemDataBound(object sender, System.Web.UI.WebControls.DataGridItemEventArgs e)
        {
            if ((e.Item.ItemType == ListItemType.Item) || (e.Item.ItemType == ListItemType.AlternatingItem))
            {
                string IsExisted = e.Item.Cells[6].Text.ToString();
                if (IsExisted == BEGDC.CC.BL.Common.CISFlag.NotExisted)
                {
                    System.Web.UI.WebControls.Image WarningImg = (System.Web.UI.WebControls.Image)e.Item.Cells[7].FindControl("CISWarning");
                    WarningImg.Visible = true;
                    WarningImg.ImageUrl = "../../images/Warning.gif";
                    WarningImg.ToolTip = "The Customer is not in CIS (该客户不是CIS成员)";
                }
                if (IsExisted == BEGDC.CC.BL.Common.CISFlag.Existed)
                {
                    System.Web.UI.WebControls.Image WarningImg = (System.Web.UI.WebControls.Image)e.Item.Cells[7].FindControl("CISWarning");
                    WarningImg.ImageUrl = "../../images/GreenWarningImg.gif";
                    WarningImg.ToolTip = "The Customer is in CIS (该客户是CIS成员)";
                    WarningImg.Visible = true;
                }
            }
        }

        void ibtnReply_Click(object sender, EventArgs e)
        {
            if (this.tbOperationFlag.Text == "reply")
            {
                IEV evService = AppContainer.Instance[ServiceConst.EVService] as IEV;
                evService.ReplyQuery(Convert.ToInt64(Request.QueryString["flowid"]), WebUtility.DeCodeString(Server, this.tbOperationContent.Text));
                Page.RegisterClientScriptBlock("", "<script>VBAlert('" + BEGDC.CC.Resource.SystemMessage.CM001 + "');window.close();</script>");
            }
        }

        private void BindASBLeaders()
        {
            //this.CBL_ASBLeader.Enabled = false;
            BEGDC.CC.BL.Common.Query.IQuery query = AppContainer.Instance[ServiceConst.QueryService] as BEGDC.CC.BL.Common.Query.IQuery;
            //DataTable table = query.GetAppASBLeadersList(this.Application.Id);
            //this.CBL_ASBLeader.DataSource = table.DefaultView;
            //this.CBL_ASBLeader.DataValueField = "DicItemID";
            //this.CBL_ASBLeader.DataTextField = "DicItemKey";
            //this.CBL_ASBLeader.DataBind();

            DataTable table2 = query.GetAppASBLeadersList2(this.Application.Id);
            this.dgASBLeaders.DataSource = table2;
            this.dgASBLeaders.DataBind();
        }
    }
}
